//
//  SubmitPurchase.m
//  DaoZiJinFu
//
//  Created by woker on 16/6/24.
//  Copyright © 2016年 iwoker. All rights reserved.
//

#import "SubmitPurchase.h"
#import "SubmitPurchaseCell.h"
#import "SubmitPurchaseHeaderView.h"
#import "SubmitPurchaseFooterView.h"
#import "VoucherCell.h"
#import "AccountBalanceCell.h"
#import "ChooseVoucher.h"
#import "TransactionDetailTableViewController.h"
#import "VoucherModel.h"
#import "PaymentConfirm.h"
#import "PurchaseBankCell.h"

#define Lable_Height 30
#define Lable_Width 90
#define Img_Height 50

@interface SubmitPurchase () <paymentDelegate> {
    BOOL haveVoucher;                       //是否有优惠券
    BOOL bankIsVisable;
    BOOL haveBalance;                       //是否有余额
    BOOL useBalance;
    NSInteger section1CellCount;            //section1cell数量
    NSInteger section2CellCount;            //section2cell数量
    NSString *investNum;                    //购买金额
    double rechargeMoney;
    NSInteger voucherID;
    double voucherMoney;
    double balanceMoney;
    double voucherLimit;
    SubmitPurchaseFooterView *footerView;
    UIView *section2headerView;             //section2头标题
    UILabel *payMoney;                      //还需支付金额
    PaymentConfirm *payment;
    
    NSMutableDictionary *orderParams;
    
    UITextField *investText;
    NSString *orderID;
    CGSize limitDescSize;
    DZBankInfo *_bankInfo;
}

@property (strong, nonatomic) UILabel *fullcutLab;

@end

@implementation SubmitPurchase

- (void)viewDidLoad {
    [super viewDidLoad];
    [self leftButton:nil];
    self.tableView.backgroundColor = BACKGROUND_COLOR;
    [self.tableView registerNib:[UINib nibWithNibName:@"SubmitPurchaseCell" bundle:nil] forCellReuseIdentifier:SUB_CELL];
    [self.tableView registerNib:[UINib nibWithNibName:@"VoucherCell" bundle:nil] forCellReuseIdentifier:VOUCHER_CELL];
    [self.tableView registerNib:[UINib nibWithNibName:@"AccountBalanceCell" bundle:nil] forCellReuseIdentifier:BALANCE_CELL];
    [self.tableView registerNib:[UINib nibWithNibName:@"PurchaseBankCell" bundle:nil] forCellReuseIdentifier:PURCHASE_BANK_CELL];
    
    investNum = @"";
    haveVoucher = NO;
    bankIsVisable = NO;
    useBalance = YES;
    voucherID = NSIntegerMax;
    haveBalance = [DZUserInfo.userInfo.account_balance doubleValue] != 0 ? YES : NO;
    
    voucherMoney = 0;
    voucherLimit = DBL_MAX;
    rechargeMoney = 0;
    balanceMoney = haveBalance == YES ? [DZUserInfo.userInfo.account_balance doubleValue] : 0;
    section1CellCount = 1;
    section2CellCount = 0;
    if (_voucherArray == nil) {
        _voucherArray = [NSArray array];
    }
    
    if (haveBalance) {
        section1CellCount++;
    } else {
        //优惠券排序
    }
    
    _bankInfo = [DZBankInfo mj_objectWithKeyValues:[DZUserInfo.userInfo.banks firstObject]];
    limitDescSize = [_bankInfo.limit_desc boundingRectWithSize:CGSizeMake(SCREEN_WIDTH-58, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:11]} context:nil].size;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(submitClick) name:@"SubmitPurchase" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(investNumChanged:) name:@"investNumChanged" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(accountSwitchChanged:) name:@"accountSwitchChanged" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadVoucherCell:) name:@"voucherChanged" object:nil];
    
}

- (void)submitClick {
    [self.view endEditing:YES];

    if ([investText.text doubleValue] < 100) {
        NSString *text = [NSString stringWithFormat:@"投资金额不能低于%.0lf元",_model.buy_min_amount];
        JSSHOW(text);
        return;
    }
    if ([investText.text doubleValue] > (_model.buy_max_amount == 0 ? _model.remaining_investment_amount : MIN(_model.buy_max_amount, _model.remaining_investment_amount))) {
        NSString *text = [NSString stringWithFormat:@"最多可购买%.0lf元",_model.buy_max_amount == 0 ? _model.remaining_investment_amount : MIN(_model.buy_max_amount, _model.remaining_investment_amount)];
        JSSHOW(text);
        return;
    }
    [investText resignFirstResponder];
    orderParams = [NSMutableDictionary dictionaryWithObjectsAndKeys:investNum,@"total_amount",_model.id,@"product_id", nil];
    if (voucherID != NSIntegerMax) {
        [orderParams setObject:[NSString stringWithFormat:@"%ld",(long)voucherID] forKey:@"uc_id"];
    } else {
        [orderParams setObject:@{} forKey:@"uc_id"];
    }
    DZHIDEHUD;
    if (rechargeMoney == 0) {
        [self createBuyOrderAction];
    } else {
        [self createRechargeOrderAction];
    }
}

- (void)createBuyOrderAction {
    JSSHOWHUD;
    DZRequestUtil *request = [[DZRequestUtil alloc] init];
    request.requestUrl = @"Order/createBuyOrder";
    request.params = orderParams;
    [DZNetAPI request:request success:^(id response) {
        JSHIDEHUD;
        DZResponse *model = [DZResponse mj_objectWithKeyValues:response];
        if (model.rt == 1) {
            DZRequestUtil *res = [[DZRequestUtil alloc] init];
            res.requestUrl = @"Order/confirmBuy";
            res.params = @{@"id":model.data[@"order_id"]?:@""};
            JSSHOWHUD;
            [DZNetAPI request:res success:^(id response) {
                JSHIDEHUD;
                DZResponse *buyModel = [DZResponse mj_objectWithKeyValues:response];
                if (buyModel.rt == 1) {
                    [CommTools setUserInfo:response];
                    TransactionDetailTableViewController *transactionDetail = [[TransactionDetailTableViewController alloc] init];
                    transactionDetail.model = _model;
                    transactionDetail.investMoney = investNum;
                    [self.navigationController pushViewController:transactionDetail animated:YES];
                }else{
                    JSSHOW(buyModel.msg);
                }
            } failure:^(NSError *error) {
                JSHIDEHUD;
                JSSHOW(LOAD_FAIL_TIP);
            }];
        }else {
            JSSHOW(model.msg);
        }
    } failure:^(NSError *error) {
        JSHIDEHUD;
        JSSHOW(LOAD_FAIL_TIP);
    }];
}

- (void)createRechargeOrderAction {
    NSDictionary *rechargeParams = @{@"bank_card_id":_bankInfo.id,
                                     @"amount":[NSString stringWithFormat:@"%.2lf",rechargeMoney]};
    //创建充值订单
    DZRequestUtil *request = [[DZRequestUtil alloc] init];
    request.requestUrl = @"Order/createRechargeOrder";
    request.params = rechargeParams;
    JSSHOWHUD;
    [DZNetAPI request:request success:^(id response) {
        JSHIDEHUD;
        DZResponse *model = [DZResponse mj_objectWithKeyValues:response];
        if (model.rt == 1) {
            orderID = model.data[@"order_id"];
            DZRequestUtil *payRequest = [[DZRequestUtil alloc] init];
            payRequest.requestUrl = @"Pay/prePay";
            payRequest.params = @{@"id":orderID};
            JSSHOWHUD;
            [DZNetAPI request:payRequest success:^(id response) {
                JSHIDEHUD;
                DZResponse *payModel = [DZResponse mj_objectWithKeyValues:response];
                if (payModel.rt == 1) {
                    payment = [PaymentConfirm showView:self.view withMobile:payModel.data[@"mobile"]];
                    payment.delegate = self;
                }else{
                    JSSHOW(payModel.msg);
                }
            } failure:^(NSError *error) {
                JSHIDEHUD;
                JSSHOW(LOAD_FAIL_TIP);
            }];
        }else{
            JSSHOW(model.msg);
        }
    } failure:^(NSError *error) {
        JSHIDEHUD;
        JSSHOW(LOAD_FAIL_TIP);
    }];
}

- (void)confirmRecharge:(NSString *)code {
    JSSHOWHUD;
    DZRequestUtil *request = [[DZRequestUtil alloc] init];
    request.requestUrl = @"Pay/confirmPay";
    request.params = @{@"sms_code":code};
    [DZNetAPI request:request success:^(id response) {
        JSHIDEHUD;
        DZResponse *model = [DZResponse mj_objectWithKeyValues:response];
        if (model.rt == 1) {
            [self payForOrder:response];
        }else{
            JSSHOW(model.msg);
        }
    } failure:^(NSError *error) {
        JSHIDEHUD;
        JSSHOW(LOAD_FAIL_TIP);
    }];
}

- (void)payForOrder:(id)responseObject {
    [payment removeFromSuperview];
    payment = nil;
    [CommTools setUserInfo:responseObject];
    [self createBuyOrderAction];
}

- (void)sendCode {
    JSSHOWHUD;
    DZRequestUtil *request = [[DZRequestUtil alloc] init];
    request.requestUrl = @"Pay/prePay";
    request.params = @{@"id":orderID?:@""};
    [DZNetAPI request:request success:^(id response) {
        JSHIDEHUD;
        DZResponse *model = [DZResponse mj_objectWithKeyValues:response];
        if (model.rt == 1) {
            JSSHOW(@"短信发送成功");
        }else{
            JSSHOW(model.msg);
        }
    } failure:^(NSError *error) {
        JSHIDEHUD;
        JSSHOW(LOAD_FAIL_TIP);
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)investNumChanged:(NSNotification *)notifi {
    investNum = [[notifi userInfo] objectForKey:@"investNum"];
    if ([investNum doubleValue] > _model.remaining_investment_amount) {
        investText.text = [NSString stringWithFormat:@"%.0f",_model.remaining_investment_amount];
    }
    investNum = investText.text;
    [self checkUseableVoucher];
    double investMoney = [investNum doubleValue];
    rechargeMoney = investMoney - voucherMoney - balanceMoney >= 0 ? investMoney-voucherMoney-balanceMoney : 0;
//    NSLog(@"%.2lf",rechargeMoney);
    payMoney.attributedText = [self payMoneyAttribute:rechargeMoney];
    [self submitBtnUseabled];
    [self checkRechargeCellVisible];
}

- (void)accountSwitchChanged:(NSNotification *)notifi {
    if ([notifi.userInfo[@"switchStatus"] boolValue] == YES) {
        useBalance = YES;
        float money = [DZNsstringUtil floatInto:[DZUserInfo.userInfo.account_balance doubleValue]];
        balanceMoney = money;
    } else {
        useBalance = NO;
        balanceMoney = 0;
    }
    rechargeMoney = [investNum doubleValue] - voucherMoney - balanceMoney >= 0 ? [investNum doubleValue]-voucherMoney-balanceMoney : 0;
    payMoney.attributedText = [self payMoneyAttribute:rechargeMoney];
    [self checkRechargeCellVisible];
}

- (void)checkUseableVoucher {
    for (int i = 0; i < _voucherArray.count; i++) {
        VoucherModel *voucherModel = _voucherArray[i];
        if ([voucherModel.limit_amount doubleValue] <= [investNum doubleValue]) {
            voucherMoney = [voucherModel.amount doubleValue];
            voucherLimit = [voucherModel.limit_amount doubleValue];
            voucherID = [voucherModel.id integerValue];
            break;
        }
    }
    if ([investNum integerValue] >= voucherLimit) {
        if ((haveBalance && section1CellCount < 3) || (!haveBalance && section1CellCount < 2)) {
            haveVoucher = YES;
            section1CellCount++;
            [self.tableView beginUpdates];
            NSArray *_tempIndexPathArr = [NSArray arrayWithObject:[NSIndexPath indexPathForRow:1 inSection:0]];
            [self.tableView insertRowsAtIndexPaths:_tempIndexPathArr withRowAnimation:UITableViewRowAnimationNone];
            [self.tableView endUpdates];
        } else {
            [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:1 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
        }
    } else {
        if (haveVoucher) {
            haveVoucher = NO;
            section1CellCount--;
            voucherMoney = 0;
            voucherLimit = DBL_MAX;
            voucherID = NSIntegerMax;
            [self.tableView beginUpdates];
            NSArray *_tempIndexPathArr = [NSArray arrayWithObject:[NSIndexPath indexPathForRow:1 inSection:0]];
            [self.tableView deleteRowsAtIndexPaths:_tempIndexPathArr withRowAnimation:UITableViewRowAnimationNone];
            [self.tableView endUpdates];
        }
    }
}

- (void)submitBtnUseabled {
    if (investNum.length) {
        footerView.submitBtn.userInteractionEnabled = YES;
        footerView.submitBtn.backgroundColor = BLUE_COLOR;
    } else {
        footerView.submitBtn.userInteractionEnabled = NO;
        footerView.submitBtn.backgroundColor = UNUSEABLECOLOR;
    }
}

- (void)checkRechargeCellVisible {
    if (rechargeMoney == 0) {
        section2headerView.hidden = YES;
    } else {
        section2headerView.hidden = NO;
    }
    if (rechargeMoney == 0 && section2CellCount == 0) {
        return;
    } else if (rechargeMoney == 0 && section2CellCount == 1) {
        section2CellCount--;
        [self.tableView beginUpdates];
        NSArray *_tempIndexPathArr = [NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:1]];
        [self.tableView deleteRowsAtIndexPaths:_tempIndexPathArr withRowAnimation:UITableViewRowAnimationNone];
        [self.tableView endUpdates];
    } else if (rechargeMoney != 0 && section2CellCount == 0) {
        section2CellCount++;
        [self.tableView beginUpdates];
        NSArray *_tempIndexPathArr = [NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:1]];
        [self.tableView insertRowsAtIndexPaths:_tempIndexPathArr withRowAnimation:UITableViewRowAnimationNone];
        [self.tableView endUpdates];
    } else {
        return;
    }
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (0 == section) {
        return section1CellCount;
    } else {
        return section2CellCount;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 1) {
        return 64+limitDescSize.height+16;
    } else {
        return 52;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (!section) {
        return 40;
    } else if (section == 1 && rechargeMoney != 0) {
        return 60;
    }
    return 4;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (1 == section) {
        return 92;
    } else {
        return 1;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell;
    if (!indexPath.section) {
        if (!indexPath.row) {
            SubmitPurchaseCell *submitCell = [SubmitPurchaseCell cellWithTableView:tableView];
            investText = submitCell.investNumText;
            cell = submitCell;
        }
        
        if (haveBalance && haveVoucher) {
            if (indexPath.row == 1) {
                VoucherCell *voucherCell = [VoucherCell cellWithTableView:tableView];
                voucherCell.fullcutLab.text = [NSString stringWithFormat:@"满%.0lf减%.0lf",voucherLimit,voucherMoney];
                _fullcutLab = voucherCell.fullcutLab;
                cell = voucherCell;
            } else {
                AccountBalanceCell *accountCell = [AccountBalanceCell cellWithTableView:tableView];
                float money = [DZNsstringUtil floatInto:[DZUserInfo.userInfo.account_balance doubleValue]];
                accountCell.accountBalance.text = [NSString stringWithFormat:@"%.2f元",money];
                cell = accountCell;
            }
        } else if (haveBalance && !haveVoucher) {
            if (indexPath.row == 1) {
                AccountBalanceCell *accountCell = [AccountBalanceCell cellWithTableView:tableView];
                float money = [DZNsstringUtil floatInto:[DZUserInfo.userInfo.account_balance doubleValue]];
                accountCell.accountBalance.text = [NSString stringWithFormat:@"%.2f元",money];
                cell = accountCell;
            }
        } else if (!haveBalance && haveVoucher) {
            if (indexPath.row == 1) {
                VoucherCell *voucherCell = [VoucherCell cellWithTableView:tableView];
                voucherCell.fullcutLab.text = [NSString stringWithFormat:@"满%.0lf减%.0lf",voucherLimit,voucherMoney];
                _fullcutLab = voucherCell.fullcutLab;
                cell = voucherCell;
            }
        }
        
    } else if (indexPath.section == 1) {
        if (rechargeMoney != 0) {
            PurchaseBankCell *bankCell = [PurchaseBankCell cellWithTableView:tableView];
            [bankCell.bankIcon sd_setImageWithURL:[NSURL URLWithString:_bankInfo.bank_logo_path?:@""] placeholderImage:[UIImage imageNamed:LOGO_PLACEHOLDER]];
            NSString *str = [NSString stringWithString:_bankInfo.bank_card_number];
            bankCell.bankTitle.text = [NSString stringWithFormat:@"%@(%@)",_bankInfo.bank_name,[str substringFromIndex:str.length-4]];
            bankCell.limitDescLab.text = _bankInfo.limit_desc;
            cell = bankCell;
        } else {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CELL"];
        }
    } else {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CELL"];
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (!section) {
        SubmitPurchaseHeaderView *headerView = [SubmitPurchaseHeaderView loadView];
        headerView.yieldLab.text = [NSString stringWithFormat:@"%.2lf%%",_annual_gains*100];
        NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
        formatter.numberStyle = kCFNumberFormatterDecimalStyle;
        headerView.investableLab.text = [NSString stringWithFormat:@"%@元",[formatter stringFromNumber:[NSNumber numberWithDouble:_remaining_investment_amount]]];
        
        return headerView;
    } else if (section == 1 && rechargeMoney != 0) {
        if (section2headerView == nil) {
            section2headerView = [self buildNeedPayView];
        }
        return section2headerView;
    }
    return nil;
}
- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    if (section) {
        footerView = [SubmitPurchaseFooterView loadView];
        footerView.submitBtn.layer.masksToBounds = YES;
        footerView.submitBtn.layer.cornerRadius = BTN_RADIUS;
        
        return footerView;
    }
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (haveVoucher) {
        if (indexPath.row == 1) {
            ChooseVoucher *chooseVoucher = [[ChooseVoucher alloc] init];
            chooseVoucher.investMoney = investNum;
            chooseVoucher.investDay = [NSString stringWithFormat:@"%.0lf",_model.day_number];
            chooseVoucher.voucherArray = [NSMutableArray arrayWithArray:_voucherArray];
            [self.navigationController pushViewController:chooseVoucher animated:YES];
        }
    }
}

- (void)reloadVoucherCell:(NSNotification *)notifi {
    VoucherModel *model = notifi.userInfo[@"voucherModel"];
    voucherMoney = [model.amount doubleValue];
    voucherLimit = [model.limit_amount doubleValue];
    voucherID = [model.id integerValue];
    _fullcutLab.text = [NSString stringWithFormat:@"满%.0lf减%.0lf",[model.limit_amount doubleValue],[model.amount doubleValue]];
    rechargeMoney = [investNum doubleValue] - voucherMoney - balanceMoney >= 0 ? [investNum doubleValue]-voucherMoney-balanceMoney : 0;
    payMoney.attributedText = [self payMoneyAttribute:rechargeMoney];
}

- (UIView *)buildNeedPayView {
    UIView *backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 60)];
    backView.backgroundColor = BACKGROUND_COLOR;
    
    UILabel *title = [[UILabel alloc] init];
    title.text = @"还需支付";
    title.textColor = DEFAULTCOLOR;
    title.font = [UIFont systemFontOfSize:14];
    [backView addSubview:title];
    
    UILabel *needPayMoney = [[UILabel alloc] init];
    needPayMoney.attributedText = [self payMoneyAttribute:rechargeMoney];
    [backView addSubview:needPayMoney];
    payMoney = needPayMoney;
    
    [title mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(backView.mas_leading).offset(12);
        make.top.equalTo(backView.mas_top).offset(15);
        make.width.equalTo(@Lable_Width);
        make.height.equalTo(@Lable_Height);
    }];
    
    [needPayMoney mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(title.mas_trailing).offset(8);
        make.top.equalTo(title.mas_top);
        make.trailing.equalTo(backView.mas_trailing).offset(-12);
        make.height.equalTo(@Lable_Height);
    }];
    
    return backView;
}

- (NSAttributedString *)payMoneyAttribute:(double)moneyString {
    NSString *yieldStr = [NSString stringWithFormat:@"%.2lf",moneyString];
    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@元",yieldStr]];
    NSDictionary *amountAttr = @{NSFontAttributeName:[UIFont systemFontOfSize:20.0f],NSForegroundColorAttributeName:ORANGECOLOR};
    NSDictionary *yuanAttr = @{NSFontAttributeName:[UIFont systemFontOfSize:14.0f],NSForegroundColorAttributeName:DEFAULTCOLOR};
    [attrStr setAttributes:amountAttr range:NSMakeRange(0, yieldStr.length)];
    [attrStr setAttributes:yuanAttr range:NSMakeRange(yieldStr.length, 1)];
    return attrStr;
}

@end
